package controller

import (
	"net/http"
	"robot/cache"
	"robot/service"
	"robot/util"
	"strconv"
)

// Login lo
func login(w http.ResponseWriter, r *http.Request) {
	switch r.Method {
	case "GET":
		http.ServeFile(w, r, "./static/login.html")
	case "POST":
		r.ParseForm()
		uid, err := strconv.Atoi(r.FormValue("name"))
		if err != nil {
			http.Redirect(w, r, r.Host+"login", http.StatusFound)
		}
		if res, err := service.CheckPassword(uid, r.FormValue("password")); err != nil || res == false {
			http.Redirect(w, r, r.Host+"login", http.StatusFound)

		} else {
			session := util.RandString(10)
			cache.Session.SetLoginSession(uid, session)
			http.SetCookie(w, &http.Cookie{
				Name:  "session",
				Value: session,
			})
		}
	}
}

func loginOut(w http.ResponseWriter, r *http.Request) {

	delete(cache.Session, "session_"+strconv.Itoa(1))
	http.Redirect(w, r, r.Host+"login", http.StatusFound)
}

func newAdminController() *http.ServeMux {
	mux := http.NewServeMux()
	return mux
}
